package net

import code.ServerChannelInitializer
import common.EnginService
import io.netty.bootstrap.ServerBootstrap
import io.netty.buffer.ByteBufAllocator
import io.netty.buffer.PooledByteBufAllocator
import io.netty.channel.Channel
import io.netty.channel.ChannelOption
import io.netty.channel.EventLoopGroup
import io.netty.channel.nio.NioEventLoopGroup
import io.netty.channel.socket.nio.NioServerSocketChannel
import java.net.InetSocketAddress

/**
 * 网络监听
 * @author King
 */
class NetAcceptor(engin: EnginService, address: InetSocketAddress) {
    private val bossGroup: EventLoopGroup
    private val workerGroup: EventLoopGroup
    private val b: ServerBootstrap
    private var channel: Channel? = null

    init {
        val handler = ServerChannelInitializer()
        handler.setEnginService(engin)
        // handler
        this.bossGroup = NioEventLoopGroup(1)
        this.workerGroup = NioEventLoopGroup()
        this.b = ServerBootstrap()
        b.option(ChannelOption.SO_BACKLOG, 128)
        b.childOption(ChannelOption.TCP_NODELAY, true)
        b.childOption(ChannelOption.SO_SNDBUF, 2048)
        b.childOption(ChannelOption.SO_RCVBUF, 8096)
        b.childOption(ChannelOption.SO_KEEPALIVE, true)
        b.childOption<ByteBufAllocator>(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)

        //		b.option(option, value)
        //		cfg.setReuseAddress(true);
        //		cfg.setTcpNoDelay(true);
        //		cfg.setKeepAlive(true);
        //		cfg.setSoLinger(0);

        b.group(bossGroup, workerGroup).channel(NioServerSocketChannel::class.java)
                .childHandler(handler)
        try {
            this.channel = b.bind(address).sync().channel()
        } catch (e: Exception) {
            this.workerGroup.shutdownGracefully()
            this.bossGroup.shutdownGracefully()
            throw RuntimeException("error", e)
        }

    }

    /**
     * 关闭服务器用
     */
    fun shutdown() {
        this.channel!!.close()
        this.workerGroup.shutdownGracefully()
        this.bossGroup.shutdownGracefully()
    }

}
